<?php

/**
 * datadump actions.
 *
 * @package    ecrm
 * @subpackage datadump
 * @author     Saul Santiago
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class datadumpActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->columns = Doctrine_Core::getTable('ContantInformation')->getColumns();

  }

  public function executeStart(sfWebRequest $request)
  {

  	$selectedColumns = array_keys($request->getPostParameter('column'));
    $filters = $request->getPostParameter('filter');
    $segments = $request->getPostParameter('segment');
//    var_dump($filters);
//    exit();
    $columnHeaders = array();
    foreach($selectedColumns as $key=>$val) {
      $columnHeaders[$key] = '"'.$val.'"';
    }
    foreach($selectedColumns as $key=>$val) {
    	$selectedColumns[$key] = 'ifnull('.$val.', "")';
    }
    for($i = 0; $i < count($segments); $i++) {
    	$columnHeaders[] = '"segment'.(intval($i)+1).'"';
    	$selectedColumns[] = '"'.$segments[$i].'"';
    }
    $columnHeadersText = implode(',',$columnHeaders);
  	$columns = implode(',',$selectedColumns);
  	$conn = Doctrine_Manager::connection();
  	$fileName = 'ecrm-'.date('Ymd-H.i.s').'.txt';
  	$path = str_replace('\\','/',getcwd()).'/datadump/';
  	$query = "SELECT ".$columnHeadersText." UNION SELECT ".$columns." INTO OUTFILE '".$path.$fileName."'
  	FIELDS TERMINATED BY '".'\t'."' LINES TERMINATED BY '".'\n'."'
  	FROM contant_information";
  	if(count($filters) > 0) {
	    foreach($filters as $key=>$val) {
	      if(strpos($query,'WHERE') !== false) {
	        $query .= ' AND '.$key.' = "'.$val.'"';
	      }
	      else {
	        $query .= ' WHERE '.$key.' = "'.$val.'"';
	      }
	    }
  	}
  	$conn->execute($query);

  	// Add fields at the top
//  	$file_data = implode("\t",$selectedColumns)."\n";
//  	$file_data .= file_get_contents($path.$fileName);
//  	file_put_contents($path.$fileName, $file_data);


  	// Set headers
  	header('Content-Type: application/octet-stream');
  	header('Content-Length: '.filesize($path.$fileName));
  	header('Content-Disposition: attachment; filename='.$fileName);
    header('Cache-Control: max-age=0');

  	// Read the file from disk
  	readfile($path.$fileName);

  	// Delete the file
  	unlink($path.$fileName);

  	exit();

  }


}
